package sample;

import freeseawind.ninepatch.javafx.FxNinePatch;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BlackBorder {

    public static ImageView get9ImageViewWithFull(String relativePath) throws Exception{
        NinePatch ninePatch = loadNinePatch(new File(relativePath));
        BufferedImage bufferedImage = ninePatch.getImage();
        WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, new WritableImage(bufferedImage.getWidth(), bufferedImage.getHeight()));
        return new ImageView(writableImage);
    }


    public static Canvas get9NewImageCanvas(String relativePath, int width, int height) {
        Canvas canvas = new Canvas(width , height);
        try {
            File file =  new File(relativePath);
            if (file != null && file.exists()) {
                GraphicsContext gc = canvas.getGraphicsContext2D();
                gc.scale(480d/1080d, 480d/1080d);
                gc.drawImage(get9ImageViewWithFull(relativePath).getImage(), 0, 0, width, height);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return canvas;
    }


    public static NinePatch loadNinePatch(File file) {
        try {
            InputStream stream = new FileInputStream(file);
            NinePatch ninePatch = NinePatch.load(stream, true, false);
            stream.close();
            return ninePatch;
        } catch (IOException e) {
            System.err.println("An error occurs during loading.");
            e.printStackTrace();
            return null;
        }
    }


    public static final Canvas get9ImageCanvas(String relativePath, int width, int height,double scaleX,double scaleY) {
        Canvas canvas = new Canvas(width * scaleX, height * scaleY);
        try {
            File file = new File( relativePath);
            if (file != null && file.exists()) {
                GraphicsContext gc = canvas.getGraphicsContext2D();
//                gc.scale(1, 0.3);
                gc.scale(scaleX, scaleY);
                Image img = null;

//                img = get9ImageViewWithFull(relativePath).getImage();
//                gc.drawImage(img,0,0,width,height);
                img = new Image(file.toURI().toURL().toString());
                FxNinePatch np = new FxNinePatch(img);
                if(height < img.getHeight()){
                    height = (int)img.getHeight();
                }
                np.drawNinePatch(gc, 0, 0, width, height);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return canvas;
    }



}
